<template>
  <div>
    <!-- 面包导航区 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="#">商品管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>分类参数 </el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 警告 -->
      <el-alert
        :closable="false"
        title="警告提示的文案"
        type="warning"
        show-icon
      >
      </el-alert>

      <!-- 选择商品 -->
      <el-row>
        <el-col span="3" class="el_opt1"><span>选择商品的分类:</span> </el-col>
        <!-- 选择商品级联按钮 -->
        <el-col span="21" class="el_opt"
          ><el-cascader
            v-model="selectCateKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader
        ></el-col>
      </el-row>

      <!-- tabs页签区 -->
      <el-tabs v-model="activeName" @tab-click="handleTabsClick">
        <!-- 动态参数页面 -->
        <el-tab-pane label="动态属性" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtn"
            @click="showAddPropsDialogflag = true"
            >添加动态参数</el-button
          >
          <el-table :data="cateManyDate" stripe border>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环标签 -->
                <el-tag
                  closable
                  @close='handleclose(index,scope.row)'
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  >{{ item }}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 与文本款切换的按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              width="500px"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  @click="showEditPropsDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="warning"
                  size="mini"
                  @click="removeProp(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性页面 -->
        <el-tab-pane label="静态管理" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtn"
            @click="showAddPropsDialogflag = true"
            >添加静态属性</el-button
          >
          <el-table :data="cateOnlyDate" stripe border>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环标签 -->
                <el-tag
                  closable
                  @close='handleclose(index,scope.row)'
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  >{{ item }}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 与文本款切换的按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              width="500px"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  @click="showEditPropsDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="warning"
                  size="mini"
                  @click="removeProp(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加属性对话框 -->
    <el-dialog
      :title="'添加' + gettittle"
      :visible.sync="showAddPropsDialogflag"
      width="50%"
      @close="addPropsDialogClose"
    >
      <el-form
        :model="addPropDate"
        :rules="addPropDaterules"
        ref="addPropDateref"
        label-width="100px"
      >
        <el-form-item :label="gettittle" prop="attr_name">
          <el-input v-model="addPropDate.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showAddPropsDialogflag = false">取 消</el-button>
        <el-button type="primary" @click="addProps">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改属性对话框 -->
    <el-dialog
      :title="'修改' + gettittle"
      :visible.sync="editAddPropsDialogflag"
      width="50%"
      @close="editPropsDialogClose"
    >
      <el-form
        :model="editPropDate"
        :rules="editPropDaterules"
        ref="editPropDateref"
        label-width="100px"
      >
        <el-form-item :label="gettittle" prop="attr_name">
          <el-input v-model="editPropDate.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editAddPropsDialogflag = false">取 消</el-button>
        <el-button type="primary" @click="editProps">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>


<script>
export default {
  data() {
    return {
      cateList: [],
      //联级选择器 子节点对应关系
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover",
      },
      //级联 选中的
      selectCateKeys: [],
      //级联 选中的 cateitem 的date
      cateManyDate: [],
      cateOnlyDate: [],

      //选中的页签
      activeName: "many",

      //添加 动态/静态 属性的对话框的 flag
      showAddPropsDialogflag: false,
      //添加 动态/静态 属性 date
      addPropDate: {
        attr_name: "",
        attr_sel: "",
      },
      //添加属性 规则
      addPropDaterules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },

      //修改属性flag
      editAddPropsDialogflag: false,
      //修改属性 data
      editPropDate: {
        attr_name: "",
        attr_sel: "",
      },
      //修改属性 规则
      editPropDaterules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },

      // tag最后面的文本框 flag
      inputVisible: false,
      //tag文本框value
      inputValue: "",
    };
  },
  methods: {
    //获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      this.cateList = res.data;
    },

    // 级联 选择框变化触发
    handleChange() {
      this.getCateInfo();

    },
    // 获取分类的三级商品信息
    async getCateInfo() {
      //   console.log(this.selectCateKeys);
      if(this.selectCateKeys.length!==3){
        this.selectCateKeys = []
        this.cateManyDate = []
        this.cateOnlyDate = []
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      );
      if (res.meta.status !== 200)
        return this.$message.error("获取分类的商品的信息失败");

      res.data.forEach((item) => {
        item.inputVisible = false;
        item.inputValue = "";
        item.attr_vals ? (item.attr_vals = item.attr_vals.split(" ")) :item.attr_vals=[];
      });

      if (this.activeName === "many") {
        this.cateManyDate = res.data;
        console.log(this.cateManyDate);
      } else if (this.activeName === "only") {
        this.cateOnlyDate = res.data;
        console.log(this.cateOnlyDate);
      }
    },

    //tabs页签区点击
    handleTabsClick() {
      this.getCateInfo();
    },

    //添加 动态/静态 属性 关闭
    addPropsDialogClose() {
      this.$refs.addPropDateref.resetFields();
    },
    //添加 动态/静态 属性 点击确认提交
    async addProps() {
      console.log(this.addPropDate.attr_name + "---" + this.activeName);

      const { data: res } = await this.$http.post(
        `categories/${this.cateId}/attributes`,
        {
          attr_name: this.addPropDate.attr_name,
          attr_sel: this.activeName,
        }
      );
      if (res.meta.status !== 201) return this.$message.error("添加失败");
      this.$message.success("添加成功");
      this.showAddPropsDialogflag = false;
      this.getCateInfo();
    },

    //修改属性 关闭
    editPropsDialogClose() {
      this.$refs.editPropDateref.resetFields();
    },
    //修改属性 打开
    async showEditPropsDialog(info) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${info.attr_id}`,
        {
          params: {
            attr_sel: this.activeName,
          },
        }
      );
      this.editPropDate = res.data;
      this.editAddPropsDialogflag = true;
    },
    //修改属性 提交
    async editProps() {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${this.editPropDate.attr_id}`,
        {
          attr_name: this.editPropDate.attr_name,
          attr_sel: this.activeName,
        }
      );
      if (res.meta.status !== 200) return this.$message.error("修改失败");
      this.$message.success("修改成功");
      this.getCateInfo();
      this.editAddPropsDialogflag = false;
    },

    //删除 属性
    async removeProp(id) {
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${id}`
      );
      if (res.meta.status !== 200) return this.$message.error("删除失败");
      this.$message.success("删除成功");
      this.getCateInfo();
    },

    //文本框失去焦点 或者enter
    async handleInputConfirm(item) {
      console.log("ok");
      if (item.inputValue.trim().length === 0) {
        item.inputValue = "";
        item.inputVisible = false;
        return;
      }
      
      //说明有内容 则做后续的上传操作
      item.attr_vals.push(item.inputValue.trim());

      item.inputValue = "";
      item.inputVisible = false;
      this.sendtonet(item)
      

    },
    //将tag的变动send到数据库
    async sendtonet(item){
      const{data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${item.attr_id}`,
      {
        attr_name:item.attr_name,
        attr_sel:item.attr_sel,
        attr_vals:item.attr_vals.join(' ')
      })
      if(res.meta.status!==200)return this.$message.error('修改失败')
      this.$message.success('修改')

    },
    //点击按钮 展示文本框
    showInput(item) {
      item.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //点击删除 对应tag
    handleclose(i,item){
      item.attr_vals.splice(i,1)
      this.sendtonet(item)

    }
  },
  created() {
    this.getCateList();
  },
  computed: {
    //判断按钮 商品分类有没有被选中
    isBtn() {
      if (this.selectCateKeys.length === 3) return false;
      else return true;
    },
    //获取 级联 选到的三级商品分类的id
    cateId() {
      if (!this.isBtn) {
        return this.selectCateKeys[2];
      } else return null;
    },
    gettittle() {
      if (this.activeName === "many") return "动态参数";
      if (this.activeName === "only") return "静态属性";
    },
  },
};
</script>


<style lang="less" scoped>
.el_opt1 {
  margin-top: 25px;
}
.el_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}
</style>